<template>
	<el-drawer style="padding: 0" v-model="visible" :show-close="false" :destroy-on-close="true" size="100%">
		<template #header="{ close, titleId, titleClass }">
			<span :id="titleId" :class="titleClass">已处理</span>
			<el-button class="btnReturn" @click="close">返回</el-button>
		</template>
		<div>
			<el-row :gutter="10">
				<el-col :span="4">
					<span>处理人：{{ todoHandleData.updater }}</span>
				</el-col>
				<el-col :span="4">
					<span>
						处理操作：
						<span style="color: #0f40f5" v-if="todoHandleData.mergeStatus == 1">合并</span>
						<span style="color: #fcca00" v-else>忽略</span>
					</span>
				</el-col>
				<el-col :span="6">
					<span>操作时间：{{ todoHandleData.updateTime }}</span>
				</el-col>
			</el-row>
		</div>
		<div style="margin: 20px 0">
			<el-button type="primary" @click="getPatientInfo">查看患者信息</el-button>
		</div>
		<div>
			<el-table :data="matchData" :show-header="false" style="width: 100%" max-height="calc(100vh - 445px)">
				<template v-for="(item, count) in matchHeaderData" :key="count">
					<el-table-column :prop="item" :class-name="getColumnClassName(count)" :width="item == 'title' ? 150 : 'auto'">
						<template #default="scope">
							<template v-if="scope.$index">
								<template v-if="item != 'title'">
									<!-- {{ matchData[scope.$index][item] }} -->
									{{ valueChange(matchData[scope.$index][item], matchData[scope.$index].title, matchData, count) }}
								</template>
								<template v-else>
									{{ matchData[scope.$index][item] }}
								</template>
							</template>
							<template v-else>
								{{ matchData[scope.$index][item] }}
							</template>
						</template>
					</el-table-column>
				</template>
			</el-table>
		</div>

		<el-drawer style="padding: 0" v-model="patientVisible" :show-close="false" :destroy-on-close="true" size="70%">
			<template #header="{ titleId, titleClass }">
				<span :id="titleId" :class="titleClass"> 当前患者数据 </span>
			</template>
			<div style="font-weight: 600; line-height: 30px; background: #f7f8fa; color: #1d2129; padding-left: 16px; margin: 10px 0">患者基本信息</div>
			<el-form disabled ref="dataFormRef" :model="dataForm" label-width="100px" class="patient-form">
				<el-row>
					<el-col :span="8">
						<el-form-item prop="pttNm" label="姓名" :rules="{ required: true }">
							<el-input v-model="dataForm.pttNm" style="width: 100%" placeholder="请输入姓名"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="gdrCd" label="性别" style="width: 100%">
							<fast-select
								v-model="dataForm.gdrCd"
								style="width: 100%"
								dict-type="mpi_gdr_cd"
								placeholder="请选择性别"
								clearable
								filterable
							></fast-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="age" label="年龄">
							<el-input style="width: 100%" v-model="dataForm.age" disabled placeholder="请输入年龄"></el-input>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col :span="8">
						<el-form-item prop="idCard" label="证件类型" style="width: 100%">
							<fast-select v-model="dataForm.idCrdCgyCd" style="width: 100%" dict-type="mpi_id_crd_cgy_cd" clearable filterable></fast-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="idCrdNo" label="证件号" :rules="{ required: true }">
							<el-input disabled style="width: 100%" v-model="dataForm.idCrdNo" placeholder="请输入证件号"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item prop="slfTelNo" label="联系电话">
							<el-input v-model="dataForm.slfTelNo" style="width: 100%" placeholder="请输入联系电话"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="aboCd" label="ABO血型">
							<fast-select
								v-model="dataForm.aboCd"
								style="width: 100%"
								dict-type="mpi_abo_cd"
								placeholder="请选择ABO血型"
								clearable
								filterable
							></fast-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="rhCd" label="Rh血型">
							<fast-select
								v-model="dataForm.rhCd"
								style="width: 100%"
								dict-type="mpi_rh_cd"
								placeholder="请选择Rh血型"
								clearable
								filterable
							></fast-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item prop="ntnlyCd" label="国籍">
							<fast-select v-model="dataForm.ntnlyCd" style="width: 100%" dict-type="mpi_ntnly_cd" placeholder="请选择国籍" clearable filterable>
							</fast-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="ntnCd" label="民族">
							<fast-select
								v-model="dataForm.ntnCd"
								style="width: 100%"
								dict-type="mpi_ntn_cd"
								placeholder="请选择民族"
								clearable
								filterable
							></fast-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="bthDt" label="出生日期">
							<el-input disabled v-model="dataForm.bthDt" style="width: 100%" placeholder="请选择出生日期"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item prop="mryCdtCd" label="婚姻状况">
							<fast-select
								v-model="dataForm.mryCdtCd"
								style="width: 100%"
								placeholder="请选择婚姻状况"
								dict-type="mpi_mry_cdt_cd"
								clearable
								filterable
							>
							</fast-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="eduCd" label="学历">
							<fast-select
								v-model="dataForm.eduCd"
								style="width: 100%"
								placeholder="请选择学历"
								dict-type="mpi_edu_cd"
								clearable
								filterable
							></fast-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item prop="age" label="单位名称">
							<el-input v-model="dataForm.wrkUntNm" style="width: 100%" placeholder="请输入工作单位名称"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="age" label="单位电话">
							<el-input v-model="dataForm.wrkUntTelNo" style="width: 100%" placeholder="请输入工作单位电话"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item prop="mdcrCgyCd" label="医疗支付方式">
							<fast-select
								v-model="dataForm.mdcrCgyCd"
								style="width: 100%"
								placeholder="请选择医疗支付方式"
								dict-type="mpi_mdcr_cgy_cd"
								clearable
								filterable
							>
							</fast-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="pfsCgyCd" label="职业类别">
							<fast-select
								v-model="dataForm.pfsCgyCd"
								style="width: 100%"
								placeholder="请选择职业类别"
								dict-type="mpi_pfs_cgy_cd"
								clearable
								filterable
							>
							</fast-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item prop="dthFlg" label="本人死亡标识">
							<el-radio-group v-model="dataForm.dthFlg" style="width: 100%">
								<el-radio :label="0">未死亡</el-radio>
								<el-radio :label="1">已死亡</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="8"></el-col>
					<el-col :span="8"></el-col>
				</el-row>
			</el-form>
			<div style="font-weight: 600; line-height: 30px; background: #f7f8fa; color: #1d2129; padding-left: 16px; margin-bottom: 10px">其他信息</div>
			<el-tabs class="patient-info-tabs" v-model="activeName" type="border-card">
				<el-tab-pane label="地址信息" name="1">
					<el-table :data="dataForm.dwdAddrVO" style="width: 100%" max-height="250" size="small">
						<el-table-column prop="addrType" label="地址信息" headerAlign="left" align="left" />
						<el-table-column prop="addr" label="地址信息" headerAlign="left" align="left" />
						<el-table-column prop="postCd" width="120" label="邮编" headerAlign="left" align="left" />
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="卡信息" name="2">
					<el-table :data="dataForm.dwdCardInfoVO" style="width: 100%" max-height="250" size="small">
						<el-table-column prop="cardType" label="卡类型" headerAlign="left" align="left" />
						<el-table-column prop="cardNo" label="卡号" headerAlign="left" align="left" />
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="证件信息" name="3">
					<el-table :data="dataForm.dwdIdCardInfoVO" style="width: 100%" max-height="250" size="small">
						<fast-table-column prop="idCrdCgyCd" label="证件类型" dict-type="mpi_id_crd_cgy_cd" headerAlign="left" align="left"></fast-table-column>
						<el-table-column prop="idCrdNo" label="证件号" headerAlign="left" align="left" />
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="联系人信息" name="4">
					<el-table :data="dataForm.dwdContactInfoVO" style="width: 100%" max-height="250" size="small">
						<fast-table-column prop="ctctRlt" label="与本人关系" dict-type="mpi_ctct_rlt_tp_cd" headerAlign="left" align="left"></fast-table-column>
						<el-table-column prop="ctctNm" label="联系人" headerAlign="left" align="left" />
						<el-table-column prop="ctctTelNo" label="联系方式" headerAlign="left" align="left" />
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="建档信息" name="5">
					<el-table :data="[]" style="width: 100%" max-height="250" size="small">
						<el-table-column prop="crtRcdOrgNm" label="建档医疗机构" headerAlign="left" align="left" />
						<el-table-column prop="crtRcdDctNm" label="建档医生" headerAlign="left" align="left" />
						<el-table-column prop="crtRcdDt" label="建档日期" headerAlign="left" align="left" />
						<el-table-column prop="crtRcdStrtDt" label="建档生效日期" headerAlign="left" align="left" />
						<el-table-column prop="rcdSttsCd" label="建档状态" headerAlign="left" align="left">
							<template #default="scope">
								{{ scope.row.rcdSttsCd == '0' ? '正常' : '异常' }}
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="签约信息" name="6">
					<el-table :data="[]" style="width: 100%" max-height="250" size="small">
						<el-table-column prop="sgnCtrctOrgNm" label="签约医疗机构" headerAlign="left" align="left" />
						<el-table-column prop="sgnCtrctDctNm" label="签约医生" headerAlign="left" align="left" />
						<el-table-column prop="sgnCtrctDt" label="签约日期" headerAlign="left" align="left" />
						<el-table-column prop="sgnCtrctStrtDt" label="签约生效日期" headerAlign="left" align="left" />
						<el-table-column prop="sgnCtrctExprDt" label="签约到期日期" headerAlign="left" align="left" />
						<el-table-column prop="sgnCtrctSttsCd" label="签约状态" headerAlign="left" align="left">
							<template #default="scope">
								{{ scope.row.sgnCtrctSttsCd == '0' ? '正常' : '异常' }}
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
			</el-tabs>
		</el-drawer>
	</el-drawer>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getExceptionData, ignoreExceptionData, getMatchInfo, mergeExceptionData } from '@/api/patient-primary/todo-handle'
import { ElMessageBox, ElMessage } from 'element-plus'
import store from '@/store'
import { getDictDataList } from '@/utils/tool'
import timeFormater from 'time-formater'
const visible = ref(false)
const title = ref('')

const dataFormRef = ref()
const dataForm = reactive({
	idCard: '',
	currAddrDscpt: '',
	pttNm: '',
	gdrCd: '',
	idCrdNo: '',
	slfTelNo: '',
	aboCd: '',
	rhCd: '',
	ntnlyCd: '',
	ntnCd: '',
	bthDt: '',
	mryCdtCd: '',
	eduCd: '',
	wrkUntNm: '',
	wrkUntTelNo: '',
	mdcrCgyCd: '',
	pfsCgyCd: '',
	joinWrkDt: '',
	age: '',
	dwdCardInfoVO: [],
	dwdContactInfoVO: [],
	dwdIdCardInfoVO: [],
	dwdAddrVO: []
})

const patientVisible = ref(false)

const todoHandleData = ref()

const pemKey = ref('')
const activeName = ref('1')
const btnType = ref('')

const matchInitData = ref([])
const matchData: any = ref([])
const matchHeaderData: any = ref([])

const tableSelIndex = ref(1)
const raidoName = ref('')

const emit = defineEmits(['close'])
let handleData = ''
const init = (data, type) => {
	todoHandleData.value = data
	btnType.value = type
	pemKey.value = data.prmKey
	visible.value = true

	// 获取原本数据
	getInitData(data)
}

const getColumnClassName = index => {
	if (index == matchHeaderData.value.length - 1) {
		return 'td-custom td-col-item-disabled'
	} else if (index) {
		return 'td-custom td-col-item' + index
	} else {
		return 'td-custom td-col-header'
	}
}

const headerData = ref([
	{
		label: '匹配分值',
		prop: 'score'
	},
	{
		label: '主索引号',
		prop: 'empi'
	},
	{
		label: '姓名',
		prop: 'pttNm'
	},
	{
		label: '性别',
		prop: 'gdrCd'
	},
	{
		label: '年龄',
		prop: 'age'
	},
	{
		label: '证件类型',
		prop: 'idCrdCgyCd'
	},
	{
		label: '证件号',
		prop: 'idCrdNo'
	},
	{
		label: '联系电话',
		prop: 'slfTelNo'
	},
	{
		label: 'ABO血型',
		prop: 'aboCd'
	},
	{
		label: 'Rh血型',
		prop: 'rhCd'
	},
	{
		label: '国籍',
		prop: 'ntnlyCd'
	},
	{
		label: '民族',
		prop: 'ntnCd'
	},
	{
		label: '出生日期',
		prop: 'bthDt'
	},
	{
		label: '现住址',
		prop: 'currAddrDscpt'
	},
	{
		label: '婚姻状况',
		prop: 'mryCdtCd'
	},
	{
		label: '学历',
		prop: 'eduCd'
	},
	{
		label: '工作单位名称',
		prop: 'wrkUntNm'
	},
	{
		label: '工作单位电话',
		prop: 'wrkUntTelNo'
	},
	{
		label: '医疗支付方式',
		prop: 'mdcrCgyCd'
	},
	{
		label: '职业类别',
		prop: 'pfsCgyCd'
	}
])
// 匹配数据
const getMatchData = async id => {
	matchHeaderData.value = []
	matchData.value = []
	matchInitData.value = []
	await getMatchInfo({ abnormalRecordId: id }).then(res => {
		let data = res.data
		data = [...res.data, handleData]
		matchInitData.value = res.data
		matchHeaderData.value = getHeader(data)
		matchData.value = getValues(data)

		let selDataIndex = ''
		matchInitData.value.forEach((item, index) => {
			if (item.empi == todoHandleData.value.empi) {
				selDataIndex = index
				return
			}
		})

		tableSelIndex.value = selDataIndex + 1
	})

	if (matchData.value.length) {
		matchHeaderData.value.forEach((element, index) => {
			if (index) {
				const dom = document.getElementsByClassName('td-col-item' + index)
				Array.from(dom).forEach(item => {
					item.style.background = ''
				})
			}
		})

		if (todoHandleData.value.mergeStatus == 1) {
			const domsel = document.getElementsByClassName('td-col-item' + tableSelIndex.value)
			Array.from(domsel).forEach((item, indexsel) => {
				item.style.background = 'rgba(87, 116, 244, 0.1)'
				// item.style.border = ' 1px solid rgb(87, 116, 244)'
				// item.style.borderColor = 'rgb(87, 116, 244)'
				item.style.border = ' 1px solid rgb(87, 116, 244)'
				if (indexsel == 0) {
					item.style.borderBottomWidth = 0
				} else if (indexsel == domsel.length - 1) {
					item.style.borderTopWidth = 0
				} else {
					item.style.borderBottomWidth = 0
					item.style.borderTopWidth = 0
				}
			})
		}
	}
}

const getHeader = data => {
	return data.reduce((pre, cur, index) => pre.concat(`value${index}`), ['title'])
}

const getValues = data => {
	return headerData.value.map((item, index) => {
		return data.reduce((pre, cur, index) => Object.assign(pre, { ['value' + index]: cur[item.prop] }), { title: item.label })
	})
}

const valueChange = (value, key, data, index) => {
	let name = ''

	let dictType = ''
	switch (key) {
		case '性别':
			dictType = 'mpi_gdr_cd'
			break
		case 'ABO血型':
			dictType = 'mpi_abo_cd'
			break
		case 'Rh血型':
			dictType = 'mpi_rh_cd'
			break
		case '证件类型':
			dictType = 'mpi_id_crd_cgy_cd'
			break
		case '国籍':
			dictType = 'mpi_ntnly_cd'
			break
		case '民族':
			dictType = 'mpi_ntn_cd'
			break
		case '婚姻状况':
			dictType = 'mpi_mry_cdt_cd'
			break
		case '学历':
			dictType = 'mpi_edu_cd'
			break
		case '医疗支付方式':
			dictType = 'mpi_mdcr_cgy_cd'
			break
		case '职业类别':
			dictType = 'mpi_pfs_cgy_cd'
			break
		default:
			dictType = ''
			break
	}
	if (dictType) {
		const data = getDictDataList(store.appStore.dictList, dictType).filter(item => item.dictValue == value)
		name = data.length ? data[0].dictLabel : ''
	} else {
		if (key == '出生日期') {
			if (value) {
				name = timeFormater(value).format('YYYY-MM-DD')
			}
		} else if (key == '年龄') {
			const num = index - 1
			name = bthDtToAge(data[12]['value' + num]).age
		} else {
			name = value
		}
	}

	return name
}

const getData = id => {
	getExceptionData({ prmKey: id }).then(res => {
		Object.assign(dataForm, res.data)

		dataForm.dwdCardInfoVO = []
		dataForm.dwdContactInfoVO = []
		dataForm.dwdIdCardInfoVO = []
		dataForm.dwdAddrVO = []
		const dwdCardInfoVO = res.data.dwdCardInfoVO
		const dwdContactInfoVO = res.data.dwdContactInfoVO
		const dwdIdCardInfoVO = res.data.dwdIdCardInfoVO
		const dwdAddrVO = res.data.dwdAddrVO
		if (dwdCardInfoVO.length) {
			dataForm.dwdCardInfoVO.push({ cardType: '城乡居民健康档案', cardNo: dwdCardInfoVO.uarrHlthRcdNo })
			dataForm.dwdCardInfoVO.push({ cardType: '社保卡', cardNo: dwdCardInfoVO.scstCrdNo })
			dataForm.dwdCardInfoVO.push({ cardType: '居民健康卡', cardNo: dwdCardInfoVO.hlthCrdNo })
			dataForm.dwdCardInfoVO.push({ cardType: '医保卡', cardNo: dwdCardInfoVO.mdcrCrdNo })
			dataForm.dwdCardInfoVO.push({ cardType: '就诊卡', cardNo: dwdCardInfoVO.vstCrdNo })
		}
		if (dwdContactInfoVO) {
			dataForm.dwdContactInfoVO.push(dwdContactInfoVO)
		}
		if (dwdIdCardInfoVO) {
			dataForm.dwdIdCardInfoVO.push(dwdIdCardInfoVO)
		}

		if (dwdAddrVO) {
			if (dwdAddrVO.currAddr) {
				dataForm.dwdAddrVO.push({ addrType: '现住址', addr: dwdAddrVO.currAddr, postCd: dwdAddrVO.currAddrPostCd })
			}
			if (dwdAddrVO.wrkUntAddr) {
				dataForm.dwdAddrVO.push({ addrType: '工作单位地址', addr: dwdAddrVO.wrkUntAddr, postCd: dwdAddrVO.wrkUntAddrPostCd })
			}
			if (dwdAddrVO.bthAddr) {
				dataForm.dwdAddrVO.push({ addrType: '出生地址', addr: dwdAddrVO.bthAddr, postCd: '' })
			}
			if (dwdAddrVO.ntvPlcAddr) {
				dataForm.dwdAddrVO.push({ addrType: '籍贯地址', addr: dwdAddrVO.ntvPlcAddr, postCd: '' })
			}
			if (dwdAddrVO.ctctAddr) {
				dataForm.dwdAddrVO.push({ addrType: '联系人地址', addr: dwdAddrVO.ctctAddr, postCd: '' })
			}
		}

		dataForm.age = bthDtToAge(dataForm.bthDt).age
	})
}

const getInitData = async data => {
	await getExceptionData({ prmKey: data.prmKey }).then(res => {
		handleData = res.data

		handleData.score = '当前数据'
		handleData.empi = todoHandleData.value.empi

		if (data.abnormalRecordId) {
			getMatchData(data.abnormalRecordId)
		}
	})
}

const getPatientInfo = () => {
	patientVisible.value = true
	activeName.value = '1'
	if (pemKey.value) {
		getData(pemKey.value)
	} else {
		ElMessage.warning('暂无患者信息')
	}
}

const tableSelChange = e => {
	tableSelIndex.value = e

	matchHeaderData.value.forEach((element, index) => {
		if (index) {
			const dom = document.getElementsByClassName('td-col-item' + index)
			Array.from(dom).forEach(item => {
				item.style.background = ''
			})
		}
	})

	const domsel = document.getElementsByClassName('td-col-item' + tableSelIndex.value)
	Array.from(domsel).forEach(item => {
		item.style.background = 'rgba(87, 116, 244, 0.1)'
	})
}

const idCardToAge = userCard => {
	let yearBirth: any = ''
	let monthBirth: any = ''
	let dayBirth: any = ''
	let sex: any = ''
	let age: any = ''
	if (userCard) {
		if (userCard.length == 15) {
			var org_birthday = userCard.substring(6, 12)
			//获取出生年月日
			yearBirth = '19' + org_birthday.substring(0, 2)
			monthBirth = org_birthday.substring(2, 4)
			dayBirth = org_birthday.substring(4, 6)
			sex = userCard.substring(14, 15) % 2 == 0 ? '2' : '1'
		} else if (userCard.length == 18) {
			//获取出生年月日 性别
			yearBirth = userCard.substring(6, 10)
			monthBirth = userCard.substring(10, 12)
			dayBirth = userCard.substring(12, 14)
			sex = userCard.substring(16, 17) % 2 == 0 ? '2' : '1'
		}
		//获取当前年月日并计算年龄
		var myDate = new Date()
		var monthNow = myDate.getMonth() + 1
		var dayNow = myDate.getDate()
		age = myDate.getFullYear() - yearBirth
		if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) {
			age--
		}
		//返回年龄、出生年月
		return { age: age, birthday: yearBirth + '-' + monthBirth + '-' + dayBirth, sex: sex }
	} else {
		return { age: '', birthday: '', sex: '' }
	}
}

const bthDtToAge = val => {
	if (val) {
		let currentYear = new Date().getFullYear() //当前的年份
		let calculationYear = new Date(val).getFullYear() //计算的年份
		const wholeTime = currentYear + val.substring(4) //周岁时间
		const calculationAge = currentYear - calculationYear //按照年份计算的年龄
		//判断是否过了生日
		if (new Date().getTime() > new Date(wholeTime).getTime()) {
			return { age: calculationAge }
		} else {
			return { age: calculationAge - 1 }
		}
	} else {
		return { age: '' }
	}
}

defineExpose({
	init
})
</script>
<style lang="scss" scoped></style>
